import { useState } from "react"
import { useHistory } from "react-router-dom"
import { Button, Space, Select, Radio, Modal, Tag, message } from "antd"
import * as apis from "../../apis/model"
import { publish } from "../../apis/appDefinition"
import useCURD from "../../hooks/useCURD"
import useModeler from "../../hooks/useModeler"
import CommonModalForm from "../../components/common/CommonModalForm"
import CommonTable, { createColumn } from "../../components/common/CommonTable"
import CommonFilterItem from "../../components/common/CommonFilterItem"

const ModelerProcesses = () => {
  const history = useHistory()
  const {
    listData,
    loading,
    handleCreate,
    handleModify,
    handleCancelForm,
    doQueryList,
    query,
    changeQueryValues,
    handleSubmit,
    formVisible,
    formTitle,
    formData,
    handleDeleteOne
  } = useCURD({
    apis,
    defaultQuery: {
      sort: 'modifiedDesc',
      filter: 'apps',
      modelType: 3
    },
    defaultSubmitValues: {
      modelType: 3
    },
    moduleName: '应用程序'
  })

  const [cascade, setCascade] = useState(false)
  const [deleteItem, setDeleteItem] = useState({})

  const handleDeleteModel = (rowData) => {
    setDeleteItem(rowData)
  }

  const handleDeleteCancel = () => {
    setCascade(false)
    setDeleteItem({})
  }

  const doDeleteModel = async () => {
    try {
      await apis.deleteOne(deleteItem.id, { cascade })
      message.success('删除成功')
      handleDeleteCancel()
      doQueryList()
    } catch (error) {
      message.error(error.message || '删除成功')
    }
  }

  const {
    commonSetting,
    cloneIngModel,
    handleClone,
    handleCancelClone,
    handleSubmitClone,
  } = useModeler({
    modelType: 3,
    doQueryList
  })

  const handlePublish = (rowData) => {
    Modal.confirm({
      title: '确定要发布',
      content: `您确定要发布应用程序定义 "${rowData.name}"? 
                注意这个应用程序定义将版本化，
                如果已经存在，则将更新工作流应用程序。`,
      onOk: async () => {
        try {
          await publish(rowData.id, { comment: '' })
          message.success('发布成功')
          doQueryList()
        } catch (error) {
          message.error(error.message || '发布失败')
        }
      }
    })
  }

  const columns = [
    ...commonSetting.modelerListColumns,
    createColumn.actions({
      width: 220,
      btns: [
        {
          text: '设计',
          onClick: (rowData) => {
            history.push(`/modeler/apps/design/${rowData.id}`)
          },
          props: {
            type: 'primary',
          }
        },
        {
          text: '发布',
          onClick: handlePublish
        },
        {
          type: 'dropdown',
          menus: [
            {
              text: '修改基本信息',
              onClick: handleModify
            },
            {
              text: '复制',
              onClick: handleClone
            },
            {
              text: '删除',
              onClick: handleDeleteModel
            }
          ]
        }
      ]
    })
  ]

  return <div className="page-wrap">
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
      formItems={commonSetting.formItems}
      initValues={formData}
    ></CommonModalForm>
    <CommonModalForm
      title="复制模型"
      visible={!!cloneIngModel.id}
      onCancel={handleCancelClone}
      onSubmit={handleSubmitClone}
      initValues={cloneIngModel}
      formItems={commonSetting.formItems}
    ></CommonModalForm>
    <Modal
      title="确定要删除？"
      visible={!!deleteItem.id}
      maskClosable={false}
      keyboard={false}
      width={400}
      onOk={doDeleteModel}
      onCancel={handleDeleteCancel}
    >
      <Radio.Group
        value={cascade}
        onChange={e => {
          setCascade(e.target.value)
        }}
      >
        <Space direction="vertical">
          <Radio value={false}>只删除当前版本 <Tag color="blue">v{deleteItem.version}</Tag></Radio>
          <Radio value={true}>也删除所有以前的版本</Radio>
        </Space>
      </Radio.Group>
    </Modal>
    <div className="page-head">
      <Space>
        <Button
          type="primary"
          onClick={handleCreate}
        >创建应用程序</Button>
      </Space>
      <Space>
        <CommonFilterItem.Select
          field="sort"
          label="排序规则"
          queryValues={query}
          onChangeQueryValues={changeQueryValues}
          options={commonSetting.sortOptions}
        ></CommonFilterItem.Select>
      </Space>
    </div>
    <div className="page-body">
      <CommonTable
        dataSource={listData}
        columns={columns}
        loading={loading}
      ></CommonTable>
    </div>
  </div>
}

export default ModelerProcesses